package com.yzq.os.spider.v.service.domain;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.yzq.os.spider.v.dao.ServerDao;
import com.yzq.os.spider.v.domain.Server;
import com.yzq.os.spider.v.util.IPUtils;

@Service
public class ServerService {
	private static final int MASTER_TYPE = 1;
	
	@Autowired
	private ServerDao serverDao;
	
	@Value("${app.contextPath}")
	private String contextPath;
	
	public List<Server> findAll() {
		return serverDao.findAll();
	}

	public boolean isLocalMaster() {
		boolean result = false;
		List<String> ips = IPUtils.getLocalIPAddress();
		List<Server> servers = findAll();
		if (CollectionUtils.isNotEmpty(ips) && CollectionUtils.isNotEmpty(servers)) {
			for (Server server : servers) {
				for (String ip : ips) {
					if (StringUtils.equals(ip, server.getIp()) && server.getType() == MASTER_TYPE) {
						result = true;
					}
				}
			}
		}
		return result;
	}

	public String getLocalIp() {
		String result = null;
		List<String> ips = IPUtils.getLocalIPAddress();
		List<Server> servers = findAll();
		if (CollectionUtils.isNotEmpty(ips) && CollectionUtils.isNotEmpty(servers)) {
			for (Server server : servers) {
				for (String ip : ips) {
					if (StringUtils.equals(ip, server.getIp())) {
						result = ip;
					}
				}
			}
		}
		return result;
	}

	public String getContextPath() {
		return contextPath;
	}
	
	

}
